"use strict";

const fs = require('fs');
const os = require('os');
const path = require('path');
const { execSync, execFileSync, spawn, spawnSync } = require("child_process");

const yaml = require('yamljs');

let backData;
let configData;

// 初始化参数
function init(projectDir, toolsDir) {
    console.log(`工程目录=${projectDir}`, `工具目录=${toolsDir}`);
    const configPath = path.join(projectDir, 'settings', 'buildConfig_Web', 'pack.config.yml');
    const backPath = path.join(projectDir, 'settings', 'buildConfig_Web', 'pack.back.json');
    if (!fs.existsSync(configPath)) {
        console.error(`配置文件不存在`, configPath);
        return;
    }
    configData = fs.readFileSync(configPath).toString();
    configData = yaml.parse(configData);
    configData.projectDir = projectDir;
    configData.toolsDir = toolsDir;

    // 输出目录
    if (os.platform() === 'darwin') { // 苹果
        configData.outputDir = configData.macBuildPath;
    } else if (os.platform() === 'win32') { // windows
        configData.outputDir = configData.winBuildPath;
    } else {
        console.error('平台不支持');
        return;
    }
    console.log('配置内容', configData);

    mkdirSync(configData.outputDir);
    // 备份内容
    if (fs.existsSync(backPath)) {
        backData = fs.readFileSync(backPath);
        try {
            backData = JSON.parse(backData);
        } catch (e) { }
    }
    if (null == backData) {
        backData = {};
    }
    backData = Object.assign({ webCode: 0}, backData);
    console.log('备份内容', backData);

    // 开始构建
    startBuild();
}
module.exports.init = init;

function startBuild() {
    let enginePath;
    if (os.platform() === 'darwin') {
        enginePath = `/Applications/CocosCreator/Creator/${configData.engineVer}/CocosCreator.app/Contents/MacOS/CocosCreator`;
    } else if (os.platform() === 'win32') {
        enginePath = `D:/CocosDashboard_1.0.18/resources/.editors/Creator/${configData.engineVer}/CocosCreator.exe`

    }
    let outputDir = path.join(configData.outputDir, configData.title);
    if (configData.webCode > backData.webCode) {
        // 构建Cocos web版本
        console.log('构建web-mobile版本开始');
        const cmd = `${enginePath} --path ${configData.projectDir} --build "title=${configData.title};platform=${configData.platform};buildPath=${outputDir};inlineSpriteFrames=${configData.inlineSpriteFrames};mergeStartScene=false;optimizeHotUpdate=false; webOrientation=${configData.orientation};md5Cache=${configData.md5Cache};debug=${configData.isDebug};embedWebDebugger=${configData.isDebug};sourceMaps=true;"`;
        try {
            execSync(cmd);
            backData.webCode = configData.webCode;
            saveConfig();
            console.log('构建web-mobile版本成功');
        } catch (e) {
            console.log(`构建web-mobile版本错误：${e.toString()}`);
            return;
        }
    }
}

function saveConfig() {
    const backPath = path.join(configData.projectDir, 'settings', 'buildConfig_Web', 'pack.back.json');
    fs.writeFileSync(backPath, JSON.stringify(backData));
    console.log('写入备份成功');
}

function mkdirSync(dirPath, mode) {
    if (fs.existsSync(dirPath)) {
        return true;
    }
    if (mkdirSync(path.dirname(dirPath), mode)) {
        fs.mkdirSync(dirPath, mode);
        return true;
    }
}

